package offer;

/**
 * @Author Elephas
 * @Date 2022/1/18
 **/
public class SearchInsert {
    public int searchInsert(int[] nums,int target){
        int left = 0,right = nums.length-1;
        int mid = left + (right - left) / 2;
        while(left <= right){
            mid = left + (right - left) / 2;
            if(nums[mid] == target){
                break;
            }else if (nums[mid] < target){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }

        // 当使用 break 退出循环时，一定是找到了 target ，返回下标
        if(left <= right){
            return mid;
        }else{
            if( nums[mid] < target){
                return mid + 1;
            }else{
                return mid;
            }
        }
    }
}
